﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Data;
using Data.Serialization;

namespace Data.OleDb
{
    public class DataService<T> : IDataService<T>
    {
        private Serializer<T> _serializer;
        //private Access_Database _db;

        public DataService()
        {
            _serializer = new Serializer<T>();
            //_db = db;
        }

        public T Add(object obj)
        {
            string insert = _serializer.CreateOleDbSqlInsertStatement();
            var parameters = _serializer.CreateOleDbParameters(obj);

            Transaction transaction = new Transaction();
            transaction.Insert(insert, parameters);

            return (T)obj;
        }
        public T Save(object obj)
        {
            string update = _serializer.CreateOleDbUpdateStatement();
            var parameters = _serializer.CreateUpdateOleDbParameters(obj);

            Transaction transaction = new Transaction();
            transaction.Update(update, parameters);

            return (T)obj;
        }

        public T Get(string select, System.Data.OleDb.OleDbParameter[] parameters)
        {
            Transaction transaction = new Transaction();

            DataRow row = transaction.GetRecord(select, parameters);

            return _serializer.MapDataRowToClass(row);
        }

        public T GetByPrimaryKey(object obj)
        {
            string select = _serializer.CreateSqlSelectByPKStatement();
            var parameter = _serializer.CreateOleDbParameterForPK(obj);

            Transaction transaction = new Transaction();

            DataRow row = transaction.GetRecord(select, parameter);

            return _serializer.MapDataRowToClass(row);
        }
        public T GetByPrimaryKey(Guid guid)
        {
            string select = _serializer.CreateSqlSelectByPKStatement();
            var parameter = _serializer.CreateOleDbParameterForPK(guid);

            Transaction transaction = new Transaction();

            DataRow row = transaction.GetRecord(select, parameter);

            return _serializer.MapDataRowToClass(row);
        }


        public List<T> GetList()
        {
            string select = _serializer.CreateSqlSelectStatement();

            Transaction transaction = new Transaction();

            DataTable table = transaction.GetRecords(select);


            return _serializer.MapDataRowCollectionToClassList(table.Rows);
        }
    }
}
